<?php
// +----------------------------------------------------------------------
// | 湘卫 [ 一切为您所想！ ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.hnxw99.com All rights reserved.
// +----------------------------------------------------------------------

namespace Home\Model;
use Think\Model;
use Think\Page;


/**
 * 学生信息模型
 */

class UserModel extends Model {

    protected $_validate = array(
        array('school_id', 'require', '所属学校不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('name', 'require', '姓名不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('admission_time', 'require', '入学时间不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('admission_time', 'getTime', self::MODEL_BOTH,'callback'),
        array('create_time', NOW_TIME, self::MODEL_INSERT),        
    );
    
    /**
     * 创建时间不写则取当前时间
     * @param  string $str 传递过来日期格式的时间，如 Y-m-d
     * @return int         时间戳
     */
    protected function getTime($str=''){
        return empty($str) ? '' : strtotime($str);
    }

    //获取列表
    public function lists($map="", $order = '`id` DESC', $field = true){
        return $this->where($map)->order($order)->select();
    }

    //获取一条数据
    public function getFind($map){
        return $this->where($map)->find();
    }

    //获取分页
    /*
     * @param  array  $map   分页条件
     * @param  array  $param 分页数组
     * @return array         列表
     */
    public function getPages($map="",$param=null){
        $psize = !empty($param['psize']) ? $param['psize']:10;
        $p = !empty($param['p']) ? $param['p']:I('p',1);
        $order = !empty($param['order']) ? $param['order']:'`id` DESC';
        $field = !empty($param['field']) ? $param['field']:true;

        $list = $this->page($p, $psize)->lists($map,$order,$field);
        $count = $this->listscount($map,$field);
        $Page = new Page($count,$psize);
        $show = $Page->show();
        return array('count'=>$count,'list'=>$list,'page'=>$show);
    }

    /* 计算列表总数
     * @param  number  $category 分类ID
     * @param  integer $status   状态
     * @return integer           总数
     */
    public function listscount($map,$field = true){
        return $this->field($field)->where($map)->count();
    }


    /**
     * 更新信息
     * @return boolean 更新状态
     */
    public function update($data){
        $data = $this->create($data);
        if(!$data){ //数据对象创建错误
            return false;
        }
        
        if(empty($data['id'])){
            $res = $this->add($data);
        }else{
            $res = $this->save($data);
        }
        return $res;
    }

    /**
     * 删除信息
     * @return boolean 删除
     */
    public function del($map,$data){
        $res = $this->where($map)->save($data);
        return $res;
    }

}
